<template>
    <div>
        <el-page-header @back="goBack" :content="$route.name"></el-page-header>
        <div class="current-flex">
            <div class="top">
                <div>启动设备</div>
                <div>紧急停止</div>
                <div>复位设备</div>
                <div>启动道闸</div>
            </div>
            <div class="second">
                <div class="second-flex">
                    <p>水位</p>
                    <p :class="water_level == '正常'?'normal':'fault'">{{water_level}}</p>
                </div>
                <div class="second-flex">
                    <p>变频</p>
                    <p :class="frequency == '正常'?'normal':'fault'">{{frequency}}</p>
                </div>
                <div class="second-flex" style="border-bottom: 0;">
                    <p>天车</p>
                    <p :class="crown == '正常'?'normal':'fault'">{{crown}}</p>
                </div>
            </div>
            <div class="third">
                <div class="third-flex">
                    <div class="third-left">设备运行状态</div>
                    <div class="third-right">
                        <el-select v-model="status" placeholder="请选择">
                            <el-option
                                v-for="(item,index) in statusList"
                                :key="index"
                                :label="item.status"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </div>
                </div>
            </div>

            <div class="save-flex">
                <el-button size="medium" type="primary" @click="save()">保 存</el-button>
            </div>
        </div>
    </div>
</template>
<script>
import "../../../../static/scss/page.scss";
// import utils from "../../util/request";
import utils from "../../../util/request";
import md from "../../../../static/js/md5";
import mqtt from "mqtt";
var instanceId = "post-cn-nif1rtd6g0h"; //实例 ID，购买后从控制台获取
var host = "post-cn-nif1rtd6g0h.mqtt.aliyuncs.com"; // 设置当前用户的接入点域名，接入点获取方法请参考接入准备章节文档，先在控制台创建实例
var port = 443; //WebSocket 协议服务端口，如果是走 HTTPS，设置443端口
var topic = "Topic_to_device/C801/C801S101D1/command"; //需要操作的 Topic,第一级父级 topic 需要在控制台申请
var frtopic = "Topic_fr_device/C801/C801S101D1/status"; //接收的topic
var useTLS = true; //是否走加密 HTTPS，如果走 HTTPS，设置为 true
var accessKey = "LTAI4Fwga2ABGrLjGMpSakrZ"; //账号的 AccessKey，在阿里云控制台查看
var secretKey = "j9aQPZpI5DOe2gik9U2u2G6E7Wtvny"; //账号的的 SecretKey，在阿里云控制台查看
var cleansession = true;
var groupId = "GID_WashVehicle_1"; //MQTT GroupID,创建实例后从 MQTT 控制台创建
var deviceId = "C801S101D1"; //设备号
var clientId = groupId + "@@@" + deviceId; //GroupId@@@DeviceId，由控制台创建的 Group ID 和自己指定的 Device ID 组合构成
var reconnectTimeout = 2000;
const options = {
    connectTimeout: 40000,
    clientId: clientId,
    clean: true
};
var client = mqtt.connect("ws://" + host + "/mqtt", options);
export default {
    data() {
        return {
            water_level: "正常", //水位
            frequency: "正常", //变频
            crown: "故障", //天车
            status: "正常运行", //设备状态
            statusList: [
                {
                    status: "正常运行",
                    value: 1
                },
                {
                    status: "停用",
                    value: 0
                }
            ],
            equipmentid: "",
        };
    },
    methods: {
        goBack: function() {
            // 页头的返回
            this.$router.go(-1);
        },
        save() {
            // 保存
            // console.log(this.status);
            utils.request("/equipment/update","post",JSON.stringify({id:this.equipmentid,state:this.status})).then(resp=>{
                console.log(resp)
                if(resp.data.code === 200){
                    this.$router.push("/equipment")
                    this.$message({
                        message: "保存成功！设备已更新",
                        type: "success"
                    })
                }else{return false}
            })
        },
        connectMqtt() {
            //连接mqtt
            let that = this;

            let options = {
                keepalive: 60, //心跳时间，0表示一直不断开，除非主动断开
                clean: false, //客户端掉线的时候，服务器必须在客户端断开之后继续存储/保持客户端的订阅状态
                connectTimeout: reconnectTimeout, // 超时时间
                clientId: groupId + "@@@" + deviceId,
                port: port //端口号
            };

            client = mqtt.connect("wss://" + host, options);
            client.on("reconnect", error => {
                // 自动重连
                console.log("正在重连:", error);
            });

            client.on("error", error => {
                // 错误
                console.log("连接失败:", error);
            });

            client.on("connect", function(data) {
                console.log("连接成功", data);
                let current_time = md.formatTime(new Date());
                console.log(current_time);
                let stringA =
                    "command_cd=4&current_time=" +
                    current_time +
                    "&device_id=" +
                    deviceId;
                let stringSignTemp = stringA + "&key=" + secretKey;
                let sign = md.md5(stringSignTemp).toUpperCase();
                let arg = {
                    device_id: deviceId, //设备号
                    command_cd: 4, //指令
                    current_time: current_time, //当前时间
                    life_time: 3600, //消息有效时间（秒）
                    version_code: "5.00", //接口版本号
                    sign: sign //签名
                };
                // client.subscribe(topic,{ qos: 0 }, function (error) {
                //     console.log(error)
                //     if (!error) {
                client.publish(topic, JSON.stringify(arg));
                console.log("发送成功");
                //     }
                // })
            });
            client.on("message", function(frtopic, message, packet) {
                // 收到消息
                console.log("packet", packet.payload.toString());
                console.log(message.toString());
                // client.end()
            });

            client.on("offline", msg => {
                // 掉线
                console.log("offline", msg);
            });
        }
    },
    mounted() {},
    created() {
        // this.connectMqtt();
        let row = JSON.parse(this.$route.query.row)
        row.water_level ? this.water_level = "正常" : this.water_level = "正常" //水位
        row.frequency === 0 ? this.frequency = "故障" : this.frequency = "正常" //变频
        row.crown === 0 ? this.crown = "故障" : this.crown = "正常", //天车
        this.status = row.state; //设备状态
        this.equipmentid = row.id;
        // console.log(row)
    },
    destroyed() {
        // console.log("123");
        // client.on("disconnect", () => {
        //     // 关闭连接
        //     console.log("end");
        // });
        // client.end(); //断开
    }
};
</script>

<style lang="scss" scoped>
.current-flex {
    display: flex;
    flex-direction: column;
    // align-items: center;
    // justify-content: center;
    width: 100%;
    // background: #fff;
}
.top {
    display: flex;
    flex-flow: row wrap;
    align-content: space-between;
    justify-content: center;
    max-width: 375px;
    height: 199px;
    // background: #fff;
    // border-radius: 8px;
    margin: 12px 0;
    padding: 50px 70px;
    box-sizing: border-box;
}

.top div {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 90px;
    height: 36px;
    border-radius: 5px;
    font-size: 15px;
    color: #fff;
    cursor: pointer;
}

.top div:nth-child(1) {
    background: #62d261;
    margin-right: 55px;
}

.top div:nth-child(2) {
    background: #ff695c;
}

.top div:nth-child(3) {
    background: #ff8a1a;
    margin-right: 55px;
}

.top div:nth-child(4) {
    background: #5ac8fa;
}

.second {
    max-width: 375px;
}
.second-flex {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 44px;
    padding: 0 16px;
    box-sizing: border-box;
}
.second-flex p {
    font-size: 16px;
}
.second-flex p:nth-child(1) {
    // width: 119px;
    color: #888;
}
.normal {
    color: #5ac8fa;
}

.fault {
    color: #ff5b53;
}

.third {
    display: flex;
    align-items: center;
    justify-content: center;
    max-width: 375px;
    height: 44px;
    padding: 0 16px;
    box-sizing: border-box;
}

.third-flex {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 375px;
}

.third-left {
    font-size: 16px;
    color: #888;
}

.third-right {
    display: flex;
    align-items: center;
    font-size: 16px;
}

.save-flex {
    display: flex;
    justify-content: center;
    width: 375px;
    margin-top: 50px;
    .el-button {
        width: 100px;
    }
}
</style>

